package com.voice.call.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.voice.call.common.Result;
import com.voice.call.common.ResultEnum;
import com.voice.call.service.NexmoService;
import com.voice.call.utils.HttpsTLS2Util;
import com.voice.call.utils.JSONUtil;
import com.voice.call.utils.StringUtil;

@Service
public class NexmoServiceImpl implements NexmoService{
	
	private final Logger log = LoggerFactory.getLogger(NexmoServiceImpl.class);
	
	private static final String APP_KEY = "a4ee2019";
	private static final String APP_SECRET = "In8PZmK8Xy7wz0yQ";
	private static final String APP_BRAND = "icall";
	
	@Override
	public boolean sendSmsCode(String phone,StringBuilder reqBuilder){
		
		try {
			
			 String urlString = "https://api.nexmo.com/verify/json";
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("api_key", APP_KEY);
			 params.put("api_secret", APP_SECRET);
			 params.put("number", phone);//发送手机号码
			 params.put("brand", APP_BRAND);//应用程序名称
			 params.put("code_length", 4);//验证码长度
			 params.put("pin_expiry", 120);//验证码有效期，单位为秒
			 params.put("lg", "en-us");//短信发送语言配置
			 log.info("验证码发送请求参数:{}",JSONUtil.mapToJson(params));
			 String jsonStr=HttpsTLS2Util.doGetTSL2(urlString, params);
			 log.info("验证码发送请求结果:{}",jsonStr);
			 
			
			 if (!StringUtil.isEmpty(jsonStr)) {
				 Map<String, Object> rsMap = JSONUtil.jsonToMap(jsonStr);
				 if (rsMap!=null && rsMap.get("status")!=null && rsMap.get("status").toString().trim().equals("0")) {
					 
					 if (reqBuilder!=null) {
						 reqBuilder.append(rsMap.get("request_id").toString().trim());
					 }
					 
				    return true;	
				 }
			 }
			
			 return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("发送短信验证码发生异常");
			return false;
		}
		
		 
	}
	
	//验证
	@Override
	public boolean verifySmsCode(String request_id,String code,String ip,StringBuilder errorTxt){
		
		try {
			
			 String urlString = "https://api.nexmo.com/verify/check/json";
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("api_key", APP_KEY);
			 params.put("api_secret", APP_SECRET);
			 params.put("request_id", request_id);//发送手机号码
			 params.put("code", code);//验证码
			 if (!StringUtil.isEmpty(ip)) {
				 params.put("ip_address", ip);//ip地址
			 }
			
			 log.info("验证码验证请求参数:{}",JSONUtil.mapToJson(params));
			 String jsonStr=HttpsTLS2Util.doGetTSL2(urlString, params);
			 log.info("验证码验证请求结果:{}",jsonStr);
			 if (!StringUtil.isEmpty(jsonStr)) {
				 
				 Map<String, Object> rsMap = JSONUtil.jsonToMap(jsonStr);
				 if (rsMap!=null && rsMap.get("status")!=null && rsMap.get("status").toString().trim().equals("0")) {
					 
					 if (errorTxt!=null) {
						 errorTxt.append(jsonStr);
					 }
					 
				    return true;	
				 }
				
			 }
			 return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("验证码验证请求发生异常");
			return false;
		}
		
	}
	
	//查询短信是否发送成功
	@Override
	public boolean searchSms(String request_id,StringBuilder statusBuilder){
		
		try {
			
			 String urlString = "https://api.nexmo.com/verify/search/json";
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("api_key", APP_KEY);
			 params.put("api_secret", APP_SECRET);
			 params.put("request_id", request_id);//发送手机号码
			 log.info("验证码查询请求参数:{}",JSONUtil.mapToJson(params));
			 String jsonStr=HttpsTLS2Util.doGetTSL2(urlString, params);
			 log.info("验证码查询请求结果:{}",jsonStr);
			 if (!StringUtil.isEmpty(jsonStr)) {
				 
				 Map<String, Object> rsMap = JSONUtil.jsonToMap(jsonStr);
				 if (rsMap!=null && rsMap.get("status")!=null ) {
					 
					 String status = rsMap.get("status").toString().trim();
					 if (statusBuilder!=null) {
						 statusBuilder.append(status);
					 }
					 /***
					  * && rsMap.get("status").toString().trim().equals("SUCCESS")
					 if (status.equals("SUCCESS")) {
						 return true;	
					 }
					 ***/
					 return true;
				 }
				
			 }
			 return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("验证码查询请求发生异常");
			return false;
		}
	}
	
	//https://github.com/nexmo-community/nexmo-java-quickstart/blob/master/src/main/java/com/nexmo/quickstart/insight/AdvancedInsight.java#L41-L68
	//https://developer.nexmo.com/api/number-insight#getNumberInsightAdvanced
	//检查手机号码 (状态为9表示没钱了)
	@Override
	public	boolean checkPhone(String phone,StringBuilder sbStatus){
		
		try {
			
			 String urlString = "https://api.nexmo.com/ni/standard/json";
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("api_key", APP_KEY);
			 params.put("api_secret", APP_SECRET);
			 params.put("number", phone);//发送手机号码
			 //log.info("Number Insight请求参数:{}",JSONUtil.mapToJson(params));
			 String jsonStr=HttpsTLS2Util.doGetTSL2(urlString, params);
			 //log.info("Number Insight请求结果:{}",jsonStr);
			 if (!StringUtil.isEmpty(jsonStr)) {
				 
				 Map<String, Object> rsMap = JSONUtil.jsonToMap(jsonStr);
				 if (rsMap!=null && rsMap.get("status")!=null&&sbStatus!=null) {
					 sbStatus.append(rsMap.get("status").toString().trim());
				}
				 if (rsMap!=null && rsMap.get("status")!=null && rsMap.get("status").toString().trim().equals("0")) {
					 
					 
					 if (rsMap.get("original_carrier")!=null) {
						
						 Map<String, Object> carrierMap=(Map<String, Object>)rsMap.get("original_carrier");
						 if (carrierMap!=null&&carrierMap.get("network_type")!=null&&carrierMap.get("network_type").toString().trim().equals("mobile")) {
							 return true;
						 }
						 
					 }
					 
					 
					
				 }
				
			 }
			 return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("Number Insight请求发生异常");
			return false;
		}
		
	}
	
	
	@Override
	public Result sendSMSMessage(String from,String to,String content){
		
		try {
			
			 String urlString="https://rest.nexmo.com/sms/json";
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("api_key", APP_KEY);
			 params.put("api_secret", APP_SECRET);
			 params.put("from", from);
			 params.put("to", to);
			 params.put("text", content);
			 log.info("短信发送请求参数:{}",JSONUtil.mapToJson(params));
			 String jsonStr=HttpsTLS2Util.doPostTSL2(urlString, params);
			 log.info("短信发送请求结果:{}",jsonStr);
			 if (!StringUtil.isEmpty(jsonStr)) {
				 Map<String, Object> rsMap = JSONUtil.jsonToMap(jsonStr);
				 if (rsMap!=null && rsMap.get("messages")!=null) {
					
					 List<Map<String, Object>> list = (List<Map<String, Object>>)rsMap.get("messages");
					 if (list!=null) {
						
						 Map<String, Object> item = list.get(0);
						 if (item.get("status")!=null&&item.get("status").toString().equals("0")) {
							return new Result();
						}
					 }
				 }
			 }
			 return new Result(ResultEnum.FAILED);
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("发送短信发生异常");
			return new Result(ResultEnum.FAILED);
		}
		
		
	}

}
